import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login', // 登录页在最前边
    name: 'login',
    component: () => import('@/views/login')
  },
  {
    path: '/', // 总体架子
    name: 'layOut',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/layout/homePage')
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/views/layout/categoryPage')
      },
      {
        path: '/cart',
        name: 'cart',
        component: () => import('@/views/layout/cartPage')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/layout/userPage')
      }
    ]
  },
  {
    path: '/myorder',
    name: 'myOrder',
    component: () => import('@/views/myorder')
  },
  {
    path: '/pay',
    name: 'pay',
    component: () => import('@/views/pay')
  },
  {
    // 动态路由传参,携带id
    path: '/prodetail/:id',
    name: 'prodetail',
    component: () => import('@/views/prodetail')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search/index.vue')
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: () => import('@/views/search/searchList.vue')
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

// 全局前置导航守卫

// 定义一个数组，把所有需要权限访问的页面存在里边
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 判断如果不是权限页面则放行
  if (!authUrls.includes(to.path)) {
    next()
    return
  }

  // 判断如果是权限页面则需要判断token是否存在
  const token = store.getters.token
  console.log(token)
  if (token) { // 如果token存在，代表已登录，直接放行
    next()
  } else { // 如果token不存在，代表未登录，重定向到login
    next('/login')
  }
})

export default router
